package com.gwtintegration.smartrf.util;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.JavaFileObject;

import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JPackage;

public class AnnotationProcessorCodeWriter extends CodeWriter {

	private final ProcessingEnvironment processingEnvironment;
	private Writer writer;

	public AnnotationProcessorCodeWriter(ProcessingEnvironment processingEnvironment) {
		this.processingEnvironment = processingEnvironment;
	}

	@Override
	public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
		throw new UnsupportedOperationException();
	}

	@Override
	public Writer openSource(JPackage pkg, String fileName) throws IOException {

		if (fileName.endsWith(".java")) {
			fileName = fileName.substring(0, fileName.indexOf(".java"));
		}

		JavaFileObject sourceFile = processingEnvironment.getFiler().createSourceFile(pkg.name() + "." + fileName);
		writer = sourceFile.openWriter();

		return writer;
	}

	@Override
	public void close() throws IOException {
		if (writer != null) {
			writer.close();
			writer = null;
		}
	}
}
